﻿using Newtonsoft.Json;

namespace Apex.ASPNETCore.GlobalException
{
    /// <summary>
    /// 创建通用返回值
    /// </summary>
    public static class GlobalResponseResultHelper
    {
        public static GlobalResponseResult<string> CreateErrorResponse(int statusCode, string? message=null)
        {
            //string? errorResponse = JsonConvert.SerializeObject(new GlobalResponseResult<string?>
            //{
            //    StatusCode = statusCode,
            //    Message = message ?? GetErrorMessageByStatusCode(statusCode),
            //    Data = null
            //});
            var errorResponse = new GlobalResponseResult<string?>
            {
                StatusCode = statusCode,
                Message = message ?? GetErrorMessageByStatusCode(statusCode),
                Data = null
            };
            return errorResponse;
        }

        /// <summary>
        /// 根据状态码返回报错信息
        /// </summary>
        /// <param name="statusCode">状态码</param>
        /// <returns></returns>
        public static string GetErrorMessageByStatusCode(int statusCode)
        {
            Dictionary<int, string> exceptionStatusCodeDic = new Dictionary<int, string>
            {
                { 400, "错误请求" },
                { 401, "没有权限" },
                { 404, "请求信息不存在" },
                { 403, "禁止访问" },
                { 500, "系统错误" }
                // 可以根据需要添加更多的状态码和对应的错误信息
            };

            // 检查字典中是否包含给定的状态码
            if (exceptionStatusCodeDic.ContainsKey(statusCode))
            {
                // 返回对应的错误信息
                return exceptionStatusCodeDic[statusCode];
            }
            else
            {
                // 如果状态码未在字典中找到，则返回默认的错误信息
                return "未知错误";
            }
        }
    }
}
